package com.fanyouzhao.ehome.web.servlet;
/**
 * @Author: fanyouzhao
 * @Date: 11:34 2021/5/7
 */

import com.alibaba.fastjson.JSON;
import com.fanyouzhao.ehome.exception.BusinessException;
import com.fanyouzhao.ehome.util.JsonResult;
import com.fanyouzhao.ehome.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

// 集中异常的处理方式
@WebServlet(name = "ExceptionHandlerServlet", value = "/exception.do")
public class ExceptionHandlerServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 在转发过程中 , 从request域中获取Exception对象( 系统异常 / BusinessException 业务异常)
        Exception e = (Exception)request.getAttribute("e");

        // 业务异常
        if(e instanceof BusinessException){
            JsonResult result = new JsonResult();
            result.setCode("0");
            result.setMsg(((BusinessException)e).getMessage());
            String s = JSON.toJSONString(request);
            // 发送给前端
            ResponseUtil.send(response,s);
        }else{
            // 记录日志
            // 目标: 把异常信息记录到error.log文件中
            // 考虑文件内容太多, 用日期作为分割依据,每天的日志放在独立的日志文件中
            // error2021-05-07.log
            String fileName = "";
            File file = new File(fileName);
            // 如果文件不存在, 就创建
            if(!file.exists()){
                file.createNewFile();
            }

            String realPath = this.getServletContext().getRealPath("error.log");
            FileWriter writer = new FileWriter(realPath,true);

            // -------------------------------
            //            // 时间 年-月-日 小时:分钟:秒
            //            // 异常类型
            //            // 异常的原因
            //            // 发生的轨迹
            //            // -------------------------------

            StringBuilder builder = new StringBuilder();


            // java中格式化时间内容的方法
            long l = System.currentTimeMillis();
            Date date = new Date();

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);

            // 异常类型
            String s = e.toString();

            String message = e.getMessage(); // 消息

            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                String s1 = stackTraceElement.toString();
            }

            // 完成字符串追加后 , 向流中写( 追加)
            writer.write(builder.toString());
            writer.flush();
            writer.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Enumeration<String> attributeNames = request.getAttributeNames();
       /* while(attributeNames.hasMoreElements()){
            String s = attributeNames.nextElement();
            System.out.println(s);
        }*/
        /*打印结果：
        javax.servlet.forward.request_uri
        javax.servlet.forward.context_path
        javax.servlet.forward.servlet_path
        javax.servlet.forward.mapping
        javax.servlet.error.status_code
        javax.servlet.error.exception_type
        javax.servlet.error.message
        javax.servlet.error.servlet_name
        javax.servlet.error.request_uri
        javax.servlet.error.exception*/

        //javax.servlet.ServletException: 自定义的测试异常信息  说明该属性返回的是一个异常对象
        Object attribute = request.getAttribute("javax.servlet.error.exception");

        String realPath = this.getServletContext().getRealPath("/log/error2.log");
        System.out.println(realPath);
        File file = new File(realPath);
        boolean newFile = file.createNewFile();
        System.out.println(newFile);
        FileWriter writer = new FileWriter(file,true);
        writer.write("");
        writer.flush();
        writer.close();
    }
}
